<template>
  <view class="container" style="height: 100vh">
    <view class="scan-card">
      <view class="scan-content">
        <wd-row>
          <wd-col>
            <wd-text text="单号：" size="28rpx" class="label-text"></wd-text>
            <wd-text :text="checkStockData.code" size="28rpx" bold></wd-text>
          </wd-col>
        </wd-row>
      </view>
    </view>

    <!-- 任务信息 -->
    <view class="task-info">
      <wd-row>
        <wd-col :span="6" class="text-right">
          <wd-text text="已盘/库存：" size="28rpx" class="label-text"></wd-text>
        </wd-col>
        <wd-col :span="18" class="text-right">
          <wd-text
            :text="checkStockData.checkNum + 'KG/' + checkStockData.stockNum + 'KG'"
            size="24rpx"
          ></wd-text>
        </wd-col>
      </wd-row>

      <wd-row>
        <wd-col :span="6" class="text-right">
          <wd-text text="当前储位：" size="28rpx" class="label-text"></wd-text>
        </wd-col>
        <wd-col :span="18" class="text-right">
          <wd-text
            :text="locationCode || '请先扫储位码'"
            size="24rpx"
            bold
            :class="{ 'text-danger': !locationCode, 'text-success': locationCode }"
          ></wd-text>
        </wd-col>
      </wd-row>
    </view>
    <wd-tabs v-model="tab" @tap="changeTabs">
      <wd-tab title="盘库产品">
        <view class="flex">
          <view class="check-list flex-1">
            <wd-card
              v-for="item in checkStockData.stockCheckDetailList"
              :key="item.id"
              custom-class="product-card"
              custom-title-class="product-card-title"
              custom-footer-class="product-card-footer"
            >
              <template #title>
                <wd-row>
                  <wd-col :span="6" :offset="18" class="text-right">
                    <wd-tag type="warning" custom-class="status-tag" mark>
                      {{
                        (item.stockNum || 0) - (item.checkNum || 0) > 0
                          ? '少'
                          : (item.stockNum || 0) == (item.checkNum || 0)
                            ? '正常'
                            : '多'
                      }}
                    </wd-tag>
                  </wd-col>
                </wd-row>
              </template>
              <view class="content">
                <wd-row>
                  <wd-col :span="10" class="text-center">
                    <wd-text text="产品名称"></wd-text>
                  </wd-col>

                  <wd-col :span="7" class="text-center">
                    <wd-text text="库存"></wd-text>
                  </wd-col>
                  <wd-col :span="7" class="text-center">
                    <wd-text text="已盘"></wd-text>
                  </wd-col>
                </wd-row>
                <wd-row>
                  <wd-col :span="10" class="text-center">
                    <wd-text :text="item.productName" size="small" bold></wd-text>
                  </wd-col>
                  <wd-col :span="7" class="text-center">
                    <wd-text
                      :text="(item.stockNum?.toFixed(2) || '0') + '' + formatUnit(item.unit)"
                      size="small"
                      bold
                    ></wd-text>
                  </wd-col>
                  <wd-col :span="7" class="text-center">
                    <wd-text
                      :text="(item.checkNum?.toFixed(2) || '0') + '' + formatUnit(item.unit)"
                      size="small"
                      bold
                    ></wd-text>
                  </wd-col>
                </wd-row>
              </view>
            </wd-card>
          </view>
          <view class="bottom-button">
            <wd-button :round="false" block class="submit-btn" @tap="handleSubmit">
              提交盘库
            </wd-button>
          </view>
        </view>
      </wd-tab>
      <wd-tab title="已扫描">
        <view class="stock-list">
          <scroll-view scroll-y style="height: 100%">
            <view class="list" style="max-height: 100%">
              <view v-if="scanProductList.length">
                <wd-swipe-action
                  v-for="(item, index) in scanProductList"
                  @tap="handleDelScan($event, item.id)"
                  :key="index"
                  class="mt-2"
                >
                  <view class="basket-card">
                    <view class="basket-header">
                      <view class="basket-title">
                        <view class="basket-code">
                          <wd-icon name="goods" size="36rpx" color="#4080ff"></wd-icon>
                          {{ item.basket }}
                        </view>
                        <view class="storage-status">
                          <text :class="['location-text']">
                            {{ item.location || '无' }}
                          </text>
                        </view>
                      </view>
                    </view>

                    <view class="basket-content">
                      <view class="info-grid">
                        <view class="info-cell">
                          <view>
                            <wd-icon name="code" size="28rpx" color="#909399"></wd-icon>
                            <text class="info-label">产品编码：</text>
                          </view>
                          <view>
                            <text class="info-value">{{ item.productCode }}</text>
                          </view>
                        </view>
                        <view class="info-cell">
                          <view>
                            <wd-icon name="bags" size="28rpx" color="#909399"></wd-icon>
                            <text class="info-label">产品名称：</text>
                          </view>
                          <view>
                            <text class="info-value">{{ item.productName }}</text>
                          </view>
                        </view>
                        <view class="info-cell">
                          <view>
                            <wd-icon name="discount" size="28rpx" color="#909399"></wd-icon>
                            <text class="info-label">数量：</text>
                          </view>
                          <view>
                            <text class="info-value">{{ item.checkNum || 0 }}</text>
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>
                  <template #right>
                    <view class="swipe-delete">
                      <wd-icon name="delete" color="#f56c6c" size="22px"></wd-icon>
                    </view>
                  </template>
                </wd-swipe-action>
              </view>
              <view v-else class="empty">
                <view class="empty-text">暂无扫描数据</view>
              </view>
            </view>
          </scroll-view>
        </view>
      </wd-tab>
    </wd-tabs>
  </view>
  <scan-code @scanSuccess="getScan" />
  <!-- <wd-button @tap="getScan('W084-1-1-1')">库码</wd-button> -->
  <!-- <wd-button @tap="getScan('W084-1-1-1')">库码</wd-button>
  <wd-button @tap="getScan('s2010120112016;PRO0000068;水果胡萝卜;20.5;吨;pur1213131;美团')">
    标签码
  </wd-button>
  <wd-button @tap="getScan('w145')">筐码</wd-button> -->
</template>

<script lang="ts" setup>
import CheckStockApi, { CheckStockSubmitForm, StockCheck } from '@/api/checkStock'
import goodsReceiptApi from '@/api/goodsReceipt'
import ScanCodeApi, { ScanPatternType } from '@/api/scanCode'
import { formatUnit } from '@/utils/unit'
import scanCode from '@/components/scanCode/scanCode.vue'
import { ref, reactive } from 'vue'
import { useToast, useMessage } from 'wot-design-uni'
const toast = useToast()
const message = useMessage()
// 上个页面传递的数据id
const checkCode = ref('')

const tab = ref()
const changeTabs = () => {
  if (tab.value === 0) {
    getCheckStockData(checkCode.value)
  } else if (tab.value === 1) {
    refreshScanList()
  }
}
// 储位，以L开头
const locationCode = ref('')
// 扫码数据列表
const scanProductList = ref<any>([])

// 重复扫码校验
const isBasketScanned = (code: string): boolean => {
  if (ScanPatternType.BASKET_CODE_TIMESTAMP.test(code)) {
    const [basket] = code.split(';')

    return scanProductList.value.some((item) => item.basket === basket)
  } else if (ScanPatternType.BASKET_CODE.test(code)) {
    return scanProductList.value.some((item) => item.basket === code)
  }
}

// 筐是否存在校验
const checkBasketExist = async (basketCode: string) => {
  try {
    const res = await goodsReceiptApi.getBasketByCode(basketCode)
    if (res.data) {
      return true
    }
    return false
  } catch (error) {
    return false
  }
}
const getScan = async (code: string) => {
  if (ScanPatternType.LOCATION_CODE.test(code)) {
    locationCode.value = code
    return
  }
  if (!locationCode.value) {
    toast.error('请先扫储位码')
    return
  }
  if (
    !(ScanPatternType.BASKET_CODE.test(code) || ScanPatternType.BASKET_CODE_TIMESTAMP.test(code))
  ) {
    return toast.error('请扫描正确的条形码')
  }
  if (ScanPatternType.BASKET_CODE.test(code)) {
    const flag = await checkBasketExist(code)

    if (!flag) return toast.error('该筐码不存在，请重新扫描')
  }
  // 重复扫码校验
  const isScanned = isBasketScanned(code)

  if (isScanned) return toast.error('该条形码已扫描或已入库，请勿重复操作')

  const processProduct = async (productInfo: CheckStockSubmitForm) => {
    const targetProduct = checkStockData.value.stockCheckDetailList?.find(
      (ele) => ele.productCode === productInfo.productCode,
    )
    if (!targetProduct) {
      return toast.error('盘库单不存在该产品')
    }
    await CheckStockApi.saveOrUpdateCheckStock({
      basket: productInfo.basket,
      checkNum: productInfo.checkNum,
      checkCode: checkStockData.value.code,
      location: locationCode.value,
      productCode: productInfo.productCode,
      productName: productInfo.productName,
    })
  }
  if (ScanPatternType.BASKET_CODE_TIMESTAMP.test(code)) {
    const [basket, productCode, productName, scanCheckNum] = code.split(';')
    if (scanCheckNum && productCode && basket) {
      await processProduct({
        basket,
        productCode,
        productName,
        checkNum: Number(scanCheckNum),
        checkCode: checkStockData.value.code,
        location: locationCode.value,
      })
    } else {
      return toast.error('无效的条形码格式')
    }
  } else {
    const { data: productInfo } = await ScanCodeApi.getBasketRecordByCode(code)
    if (!productInfo?.productCode) {
      return toast.error('获取产品信息失败')
    }
    await processProduct({
      productCode: productInfo.productCode,
      productName: productInfo.productName,
      basket: productInfo.parentCode,
      checkNum: productInfo.qty,
      checkCode: checkStockData.value.code,
      location: locationCode.value,
    })
  }
  await refreshScanList()
}

// 更新扫码列表
const refreshScanList = async () => {
  CheckStockApi.getBasketDetailByCheckCode(checkStockData.value.code).then((res) => {
    scanProductList.value = res.data
  })
}
const queryPage = reactive({
  pageNum: 1,
  pageSize: 10,
})
const checkStockData = ref<StockCheck>({})
const getCheckStockData = (code: string) => {
  CheckStockApi.getCheckStockList({ ...queryPage, code })
    .then((res: any) => {
      checkStockData.value = res.data.list[0]
    })
    .catch((err) => {
      console.log(err)
    })
}
// 删除扫码数据
const handleDelScan = (event, id) => {
  if (event.value === 'right') {
    message
      .confirm({
        msg: '确定删除吗？',
        title: '警告',
      })
      .then(() => {
        CheckStockApi.deleteCheckStock(id).then(() => {
          toast.success('删除成功')
        })
      })
      .finally(() => {
        refreshScanList()
      })
  }
}
// 提交盘库
const handleSubmit = () => {
  message
    .confirm({
      msg: '确定提交吗？',
      title: '警告',
    })
    .then(() => {
      CheckStockApi.submitCheckStock(checkStockData.value.id).then(() => {
        toast.success('提交成功')
        uni.reLaunch({ url: '/pages/checkStock/checkStock' })
      })
    })
}

onLoad((options) => {
  checkCode.value = JSON.parse(options.code)
  getCheckStockData(checkCode.value)
  refreshScanList()
  console.log(checkCode.value)
})

onShow(() => {})

// 页面隐藏注销事件
onHide(() => {})
</script>

<style lang="scss" scoped>
$primary-color: #3e7bfa;
$secondary-color: #36b8c2;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$background-color: #f5f7fa;
$card-background: #ffffff;
$text-primary: #303133;
$text-secondary: #606266;
$border-color: #ebeef5;
$box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
$detail-primary: #1989fa;
$detail-success: #00b578;
$detail-danger: #ff4d4f;
$detail-warning: #ff9f00;
$card-gradient: linear-gradient(145deg, #ffffff, #f8faff);
$primary-color: #3e7bfa;
$secondary-color: #36b8c2;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$background-color: #f5f7fa;
$card-background: #ffffff;
$text-primary: #303133;
$text-secondary: #606266;
$border-color: #ebeef5;
$box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
page {
  height: 100%;
}
.product-card {
  padding: 10px;
}
:deep(.wd-card__footer) {
  padding: 0;
}
:deep(.wd-card__title-content) {
  padding: 0;
}
.container {
  display: flex;
  flex-direction: column;
  height: 100%;

  .scan-card {
    background: $card-gradient;

    .scan-content {
      padding: 15rpx;
      text-align: center;
      box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
      .scan-text {
        position: relative;
        margin-bottom: 48rpx;
        font-size: 24rpx;
        font-weight: 500;
        color: $text-primary;
      }

      :deep(.wd-button) {
        height: 96rpx;
        font-size: 32rpx;
        letter-spacing: 2rpx;

        box-shadow: 0 8rpx 24rpx rgba($detail-primary, 0.2);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

        &:active {
          box-shadow: 0 4rpx 16rpx rgba($detail-primary, 0.3);
          transform: scale(0.96);
        }
      }
    }
  }
}

.nav-bar {
  position: relative;
  display: flex;
  flex-shrink: 0;
  align-items: center;
  height: 88rpx;
  padding: 0 32rpx;
  background-color: #4c84ff;
}

.back-icon {
  width: 20px;
  height: 20px;
}

.nav-title {
  position: absolute;
  left: 50%;
  font-size: 16px;
  font-weight: 500;
  color: #ffffff;
  transform: translateX(-50%);
}

.content {
  flex: 1;
  overflow: auto;
}

.task-info {
  padding: 24rpx 32rpx;
  margin-bottom: 20rpx;
  background-color: #ffffff;
  .text-danger {
    color: $danger-color;
  }
  .text-success {
    color: $success-color;
  }
}

.task-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.task-item:last-child {
  margin-bottom: 0;
}

.label {
  font-size: 14px;
  color: #666666;
}

.value {
  font-size: 14px;
  color: #333333;
}

.delete-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 0 16px;
  color: red;
}
.check-list {
  margin: 20rpx;
  margin-bottom: 120rpx;

  .product-card {
    margin: 20rpx 0;
    overflow: hidden;
    border-radius: 16rpx;
    box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.08);
    transition: transform 0.3s ease;

    &:active {
      transform: translateY(4rpx);
    }

    .content {
      padding: 20rpx;

      .wd-row {
        padding: 12rpx 0;
        margin: 16rpx 0;

        border-radius: 8rpx;
      }

      .wd-text[bold] {
        font-size: 28rpx;
        color: $text-primary;
      }
    }
  }

  .status-tag {
    margin-right: 20rpx;
    &[type='warning'] {
      color: #faad14;
      background: #fff7e6 !important;
    }
  }
}

.bottom-button {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.stock-list {
  .list {
    .basket-card.error-border {
      border: 1px solid #f56c6c;
    }
    .basket-card {
      padding: 20rpx;
      margin: 0 20rpx;
      border: 1px solid #eeeeee;
      border-radius: 10rpx;
      box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
      .basket-header {
        .basket-title {
          display: flex;
          align-items: center;
          justify-content: space-between;
          .basket-code {
            font-size: 15px;
            font-weight: 500;
            color: #303133;
          }
        }
        .storage-status {
          display: flex;
          align-items: center;

          .location-text {
            margin-left: 10rpx;
            font-size: 28rpx;
            &.error-text {
              color: #f56c6c;
            }
          }
        }
      }
      .basket-content {
        .info-grid {
          display: flex;
          flex-direction: column;

          .info-cell {
            display: flex;

            align-items: center;
            justify-content: space-between;
            padding: 12rpx 20rpx;

            border-radius: 8rpx;

            .info-label {
              margin: 0 10rpx 0 20rpx;

              color: #909399;

              white-space: nowrap;
            }

            .info-value {
              overflow: hidden;

              font-weight: 500;

              color: #303133;

              text-overflow: ellipsis;
            }

            .wd-icon {
              flex-shrink: 0;
            }
          }
        }

        .error-msg {
          grid-column: span 2;
        }
      }
    }
    .swipe-delete {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 200rpx;
      height: 100%;
      padding: 0 20rpx;
      font-size: 28rpx;
      color: #f56c6c;
    }
  }
  .empty {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    padding: 20rpx;
    color: #909399;
    .empty-text {
      font-size: 14px;
      font-weight: 500;
      color: #909399;
    }
  }
}
</style>
